import { initWithEncrypt, removeScreenWatermark } from '@/utils/lib';

import styled from '@emotion/styled';
import { Button, Checkbox, Form, Input } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import ErrorAlert from '../Alert';

import AgentService, { Code, IEvent } from '@/modules/Agent';
import Message from '@/modules/Message';
import ChangePassword from './ChangePassword';

const LoginContainer = styled.div`
	position: absolute;
	width: 600px;
	height: 400px;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	border: 1px solid #eee;
	padding: 20px;
	background: #ffffff;
	border-radius: 10px;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.12);
`;

const LoginHeader = styled.h2`
	text-align: center;
	font-weight: 700;
	padding: 10px 0;
`;

const Login: React.FC = () => {
	const { t } = useTranslation();
	const [loginData, setLoginData] = useState<{ username: string; password: string; org: string; remember: boolean }>({ username: '', password: '', org: '', remember: true });
	const [showChangePassword, setShowChangePassword] = useState<boolean>(false);
	const [form] = Form.useForm();
	
	useEffect(() => {
		const username = localStorage.getItem('agent_user_name') || '';
		const password = localStorage.getItem('agent_pwd') || '';
		const org = localStorage.getItem('agent_org') || '';
		if (username && password && org) {
			setLoginData({ ...loginData, username, password, org });
			AgentService.setLoginData({ username, password, org });
			form.setFieldsValue({ username, password, org });
		}
		AgentService.addEventListener(resp => {
			if (resp.event === IEvent.LOGIN && resp.data.code === Code.LOGIN_SUCCESS) {
				go();
			}
			if (resp.event === IEvent.LOGIN && resp.data.code === Code.LOGIN_ERROR) {
				console.log('LOGIN_ERROR', resp.data);
				const { isInitPwd, isExpired } = resp.data.data;
				if (isInitPwd === 'Y') {
					Message.warning(`您的密码属于初始密码，请重新设置`);
					setShowChangePassword(true);
				} else if (isExpired) {
					Message.warning(`您当前使用的登录密码已过期，请更新密码！`);
					setShowChangePassword(true);
				}
			}
		});

		AgentService.configure.setPocSetting({
			autoAnswer: getQueryString('autoAnswer') === '1' ? true : false,
			autoReady: getQueryString('autoReady') === '1' ? true : false,
			autoCheckin: getQueryString('autoCheckin') === '1' ? true : false
		});

		if (getQueryString('agentName') && getQueryString('pwd') && getQueryString('org')) {
			AgentService.setLoginData({ username: getQueryString('agentName'), password: getQueryString('pwd'), org: getQueryString('org') });
			AgentService.loginSystem();
		}
		// 去除屏幕水印
		removeScreenWatermark();

		return () => {
			window.removeEventListener('popstate', () => {}, false);
			AgentService.removeEventListener();
		};
	}, []);

	const getQueryString = (name: string) => {
		let search = window.location.href;
		let pattern = new RegExp('[?&]' + name + '=([^&]+)', 'g');
		let matcher = pattern.exec(search);
		let items = '';
		if (null != matcher) {
			try {
				items = decodeURIComponent(decodeURIComponent(matcher[1]));
			} catch (e) {
				try {
					items = decodeURIComponent(matcher[1]);
				} catch (e) {
					items = matcher[1];
				}
			}
		}
		return items;
	};

	const nav = useNavigate();
	const onFinish = async (values: any) => {
		console.log('Success:', values);
		const { username, password, org, remember } = values;
		AgentService.setLoginData({ username, password, org });
		try {
			await AgentService.loginSystem();
			if (remember) {
				localStorage.setItem(`agent_user_name`, username);
				localStorage.setItem(`agent_pwd`, password);
				localStorage.setItem(`agent_org`, org);
			}
			localStorage.setItem(`agent_login_time`, new Date().getTime().toString());
		} catch (error) {
			console.log(error);
		}
	};

	const go = () => {
		nav('/', { replace: false });
	};

	const onFinishFailed = (errorInfo: any) => {
		console.log('Failed:', errorInfo);
	};

	const [, updateState] = useState<any>();
	const handleForceupdateMethod = useCallback(() => updateState({}), []);

	const setErrorView = (visible: boolean) => {
		AgentService.setErrorView(visible);
		handleForceupdateMethod();
	};

	return (
		<div className="widget-login-container">
			<LoginContainer>
				<LoginHeader>{t('agent-login')}</LoginHeader>
				<Form name="basic" form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} initialValues={loginData} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off">
					<Form.Item label={t('user-name')} name="username" rules={[{ required: true, message: t('user-name-invalid') as string }]}>
						<Input onPressEnter={e => e.preventDefault()} />
					</Form.Item>

					<Form.Item label={t('password')} name="password" rules={[{ required: true, message: t('password-invalid') as string }]}>
						<Input.Password onPressEnter={e => e.preventDefault()} />
					</Form.Item>

					<Form.Item label={t('org')} name="org" rules={[{ required: true, message: t('org-invalid') as string }]}>
						<Input onPressEnter={e => e.preventDefault()} />
					</Form.Item>

					<Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 4, span: 16 }}>
						<Checkbox>{t('remeber-password')}</Checkbox>
					</Form.Item>

					<Form.Item wrapperCol={{ offset: 7 }}>
						<Button type="primary" htmlType="submit" style={{ width: '240px' }}>
							{t('login')}
						</Button>
					</Form.Item>
				</Form>
			</LoginContainer>
			{AgentService.errorView ? <ErrorAlert setErrorView={setErrorView} /> : undefined}
			{showChangePassword && <ChangePassword onClose={() => setShowChangePassword(false)} />}
		</div>
	);
};

export default Login;
